<template>
  <div class="page-container">
    
    <div class="list-page">
      <!-- 搜索和操作区域 -->
      <div class="filter-area">
        <div class="search-area">
          <el-input
            v-model="searchValue"
            placeholder="请输入设备名称搜索"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="operation-area">
          <el-button 
            class="custom-button primary-button"
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>新增设备
          </el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        height="calc(100vh - 250px)" 
        :header-cell-style="{ background: 'var(--el-bg-color-page)' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="设备名称" prop="deviceName" min-width="150" />
        <el-table-column label="设备类型" prop="deviceType" width="150" align="center" />
        <el-table-column label="安装位置" prop="installLocation" width="150" align="center" />
        <el-table-column label="纬度" prop="lat" width="150" align="center">
          <template #default="scope">
            {{ Number(scope.row.lat).toFixed(6) }}
          </template>
        </el-table-column>
        <el-table-column label="经度" prop="lon" width="150" align="center">
          <template #default="scope">
            {{ Number(scope.row.lon).toFixed(6) }}
          </template>
        </el-table-column>
        <el-table-column label="设备状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '在线' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="生产厂商" prop="manufacturer" width="150" align="center" />
        <el-table-column label="设备型号" prop="sn" width="150" align="center" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑/新增弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        width="60%"
        top="5vh"
        destroy-on-close
        :show-header="false"
      >
        <div style="height: 500px;display: flex;justify-content: center;align-items: center;">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120px"
            class="device-form"
          >
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
            <el-form-item label="设备类型" prop="deviceType">
              <el-input v-model="form.deviceType" placeholder="请输入设备类型" />
            </el-form-item>
            <el-form-item label="安装位置" prop="installLocation">
              <el-input v-model="form.installLocation" placeholder="请输入安装位置" />
            </el-form-item>
            <el-form-item label="纬度" prop="lat">
              <el-input-number 
                v-model="form.lat" 
                :precision="6"
                :step="0.000001"
                placeholder="请输入纬度"
              />
            </el-form-item>
            <el-form-item label="经度" prop="lon">
              <el-input-number 
                v-model="form.lon" 
                :precision="6"
                :step="0.000001"
                placeholder="请输入经度"
              />
            </el-form-item>
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择设备状态">
                <el-option label="在线" value="在线" />
                <el-option label="离线" value="离线" />
              </el-select>
            </el-form-item>
            <el-form-item label="生产厂商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入生产厂商" />
            </el-form-item>
            <el-form-item label="设备型号" prop="sn">
              <el-input v-model="form.sn" placeholder="请输入设备型号" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSubmit">确定</el-button>
              <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { getDeviceInfo, addDeviceInfo, updateEDeviceInfo, deleteDeviceInfo, getDeviceDetail } from '@/api/bridge/bisc/equipment'
import BridgeVerticalTabNav from './components/BridgeVerticalTabNav.vue'

// 查询参数
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchValue = ref('')

// 弹窗控制
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')

// 表单数据
const formRef = ref()
const form = ref({
  id: '',
  deviceName: '',
  deviceType: '',
  installLocation: '',
  lat: 0,
  lon: 0,
  status: '在线',
  manufacturer: '',
  sn: ''
})

// 表单校验规则
const rules = {
  deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  deviceType: [{ required: true, message: '请输入设备类型', trigger: 'blur' }],
  installLocation: [{ required: true, message: '请输入安装位置', trigger: 'blur' }],
  lat: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
  lon: [{ required: true, message: '请输入经度', trigger: 'blur' }],
  status: [{ required: true, message: '请选择设备状态', trigger: 'change' }],
  manufacturer: [{ required: true, message: '请输入生产厂商', trigger: 'blur' }],
  sn: [{ required: true, message: '请输入设备型号', trigger: 'blur' }]
}

// 获取列表数据
const getList = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchValue.value
    }
    const res = await getDeviceInfo(params)
    tableData.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getList()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    id: '',
    deviceName: '',
    deviceType: '',
    installLocation: '',
    lat: 0,
    lon: 0,
    status: '在线',
    manufacturer: '',
    sn: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: any) => {
  try {
    const res = await getDeviceDetail(row.id)
    form.value = res.data
    dialogType.value = 'edit'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
  }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该设备信息吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDeviceInfo(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addDeviceInfo(form.value)
          ElMessage.success('新增成功')
        } else {
          await updateEDeviceInfo(form.value)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('保存失败:', error)
      }
    }
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.list-page {
  flex: 1;
  padding: 20px;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: auto;
}

.filter-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  padding: 16px;
  border-radius: 4px;

  .search-input {
    width: 300px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
  background: var(--el-bg-color-overlay);
}

.el-dialog {
  border-radius: 12px;
  
  :deep(.el-dialog__body) {
    padding: 24px;
  }
}

.device-form {
  width: 100%;
  padding: 20px;
}

.operation-area {
  display: flex;
  gap: 12px;
  
  .custom-button {
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      width: 0;
      height: 0;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      transform: translate(-50%, -50%);
      transition: width 0.6s ease, height 0.6s ease;
    }
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      
      &::before {
        width: 300px;
        height: 300px;
      }
    }
    
    &:active {
      transform: translateY(1px);
    }
  }

  .primary-button {
    background: var(--el-color-primary);
    border-color: var(--el-color-primary);
    color: white;
    
    &:hover {
      background: var(--el-color-primary-light-3);
      border-color: var(--el-color-primary-light-3);
    }
  }
}
</style>